/**
 * 柱状图表的绘制
 *
 * @param _id       --容器ID
 * {
 *      "url":"数据来源",
 *      "params": {"变量名": "值"}
 * }
 * or
 * {
 *      "xList": ["名称1", "名称2", "名称3"],
 *      "yList": ["值1", "值2", "值3"]
 * }
 * @param _source       --数据源
 * {
 *      "title": "图表标题",
 *      "yTitle": "y轴标题",
 *      "xBaseCount": "x轴基量（单页面x轴显示数量）",
 *      "series": [
 *          {"name": "项名1", "sourceName": "数据源键名1"},
 *          {"name": "项名2", "sourceName": "数据源键名2"}
 *      ]
 * }
 * @param _config       --常用变量
 * @param _newOption    --自定义新的option
 * @constructor
 *
 * create by cd 20161219
 * modify by ck 20161228    提供多种数据来源方式，项名可以从数据源读取，默认参数更改，优化注释
 * modify by ck 20170103    可传ID或对象，方法返回ECharts对象（以便绑定事件，避免重复初始化）
 * modify by ck 20170104    去除对象，防止数据残留
 */
function XHBarChart(_id, _source, _config, _newOption) {
    //如果为string则转为object(转换字符串形式json)
    if(typeof _source == 'string') _source = eval('(' + _source + ')');

    //初始化echarts实例
    var myChart = echarts.init(document.getElementById(_id));
    myChart.showLoading();

    //如果数据源定义了url，则根据url获取数据，否则直接显示
    if(_source.url){
        var _params = _source.params ? _source.params : {};
        $.ajax({
            type: 'POST',               //POST/PUT/DELETE/HEAD
            url: _source.url,
            data: _params,
            async: true,
            dataType: 'json',
            success: function (data) {	//成功响应的回
                dealChart(data);
            }
        });
    }
    else{
        dealChart(_source);
    }
    return myChart;

    //处理参数并渲染
    function dealChart(_data){
        myChart.hideLoading();
        // 指定图表的配置项和数据
        var colors = ['#59ADF3', '#AF89D6', '#FF999A', '#FFCC67', '#86D560'];
        var _series = [], _tempSeries = [], _legends = [], _count = 10;
        var xBaseCount = _config.xBaseCount ? _config.xBaseCount : 10;

        $.each(_data, function (key, value) {
            _count = value.length;
            return false;
        });

        if(_data.series){
            _tempSeries = _data.series;
        }
        if(_config.series){
            _tempSeries = _config.series;
        }
        $.each(_tempSeries, function (index, source) {
            _series.push({
                name: source.name,
                type: 'bar',
                data: _data[source.sourceName],
                label: {
                    normal: {
                        show: true,
                        position: 'top',
                        textStyle: {
                            fontWeight: 'bolder',
                            fontSize: '12'
                        }
                    }
                }
            });
            _legends.push(source.name);
        });

        var option = {
            color: colors,
            title: {
                text: _config.title ? _config.title : '',
                textStyle: {
                    fontSize: 20
                },
                left: '7%'
            },
            tooltip: {
                trigger: 'axis'
            },
            toolbox: {
                itemSize: 20,
                show: true,
                right: '1%',
                feature: {
                    mark: {show: true},
                    dataView: {show: true, readOnly: false},
                    magicType: {show: true, type: ['line', 'bar']},
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            calculable: true,
            legend: {
                data: _legends,
                itemGap: 10,
                itemHeight: 20,
                itemWidth: 20

            },
            grid: {
                top: '15%',
                left: '3%',
                right: '5%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: [{
                //设置字体倾斜
                axisLabel: {
                    interval: 0,
                    rotate: 15,//倾斜度 -90 至 90 默认为0
                    margin: 20,
                    textStyle: {
                        fontWeight: "bolder",
                        color: "#000000",
                        fontSize: 14
                    }
                },
                type: 'category',
                axisTick: {
                    alignWithLabel: true
                },
                data: _data.xList
            }],
            yAxis: [{
                type: 'value',
                splitArea: {show: true},
                name: _config.yTitle ? _config.yTitle : '总量',
                min: 0,
                position: 'left',
                axisLabel: {
                    formatter: '{value}'
                }
            }],
            dataZoom: [
                {
                    show: true,
                    start: 0,//数据窗口范围的起始百分比
                    end: (xBaseCount / _count) * 100
                },
                {
                    type: 'inside',
                    start: 0,
                    end: 100
                },
                {
                    show: true,
                    yAxisIndex: 0,
                    filterMode: 'empty',
                    width: 20,
                    height: '65%',
                    showDataShadow: false,
                    left: '98%'
                }
            ],
            series: _series
        };
        //如果有额外配置，则合并，以额外配置为准
        if (_newOption) option = $.extend(true, option, _newOption);

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }
}


/**
 * 线状图表的绘制
 *
 * @param _dom          --dom节点
 * @param _url          --json的路径
 * @param _params       --传入参数
 * @param _config       --定义变量      title:标题    yTitle：y轴标题     xBaseCount：x轴基量     series: 图表项含有name（名称）  sourceName（在json中的名称）对象数组
 * @param _newOption    --自定义新的option
 * @constructor
 *
 * create by cd 20161219
 */
function XHLineChart(_dom, _url, _params, _config, _newOption) {
    var xBaseCount = _config.xBaseCount ? _config.xBaseCount : 10;
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(_dom);
    // 指定图表的配置项和数据
    var colors = ['#59ADF3', '#AF89D6', '#FF999A', '#FFCC67', '#86D560'];
    myChart.showLoading();
    $.ajax({
        type: 'POST',  //POST/PUT/DELETE/HEAD
        url: _url,
        data: _params,  //{k:v} 请求数据
        success: function (_data) {	//成功响应的回调
            myChart.hideLoading();
            var _series = [];
            var _legends = [];
            var _count;
            $.each(_data, function (key, value) {
                _count = value.length;
                return false;
            });
            $.each(_config.series, function (index, source) {
                _series.push({
                    name: source.name,
                    type: 'line',
                    data: _data[source.sourceName],
                    label: {
                        normal: {
                            show: true,
                            position: 'top',
                            textStyle: {
                                fontWeight: 'bolder',
                                fontSize: '12'
                            }
                        }
                    }
                });
                _legends.push(source.name);
            });
            option = {
                color: colors,
                title: {
                    text: _config.title ? _config.title : '',
                    textStyle: {
                        fontSize: 25
                    },
                    left: '10%'
                },
                tooltip: {
                    trigger: 'axis'
                },
                toolbox: {
                    itemSize: 25,
                    show: true,
                    right: '10%',
                    feature: {
                        mark: {show: true},
                        dataView: {show: true, readOnly: false},
                        magicType: {show: true, type: ['line', 'bar']},
                        restore: {show: true},
                        saveAsImage: {show: true}
                    }
                },
                calculable: true,
                legend: {
                    data: _legends,
                    itemGap: 40,
                    itemHeight: 20,
                    itemWidth: 30

                },
                grid: {
                    top: '10%',
                    left: '10%',
                    right: '10%',
                    bottom: '10%',
                    containLabel: true
                },
                xAxis: [{
                    //设置字体倾斜
                    axisLabel: {
                        interval: 0,
                        rotate: 15,//倾斜度 -90 至 90 默认为0
                        margin: 20,
                        textStyle: {
                            fontWeight: "bolder",
                            color: "#000000",
                            fontSize: 14
                        }
                    },
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: _data.xList
                }],
                yAxis: [{
                    type: 'value',
                    splitArea: {show: true},
                    name: _config.yTitle ? _config.yTitle : '总量',
                    min: 0,
                    position: 'left',
                    axisLabel: {
                        formatter: '{value}'
                    }
                }],
                dataZoom: [
                    {
                        show: true,
                        start: 0,//数据窗口范围的起始百分比
                        end: (xBaseCount / _count) * 100
                    },
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                    {
                        show: true,
                        yAxisIndex: 0,
                        filterMode: 'empty',
                        width: 20,
                        height: '100%',
                        showDataShadow: false,
                        left: '92%'
                    }
                ],
                series: _series
            };
            if (_newOption) option = $.extend(true, option, _newOption);
            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
        },
        error: function () {  //失败响应的回调
            console.log('失败响应的回调.');
            console.log(arguments);
        }
    });
}


/**
 *混合图表的绘制
 *
 * @param _dom      --dom节点
 * @param _url      --json的路径
 * @param _params       --传入参数
 * @param _config       --定义变量      title:标题    yTitle：y轴标题数组     xBaseCount：x轴基量     series: 图表项含有name  sourceName对象数组 第一个为柱状 第二个为线状
 * @param _newOption    --自定义新的option
 * @constructor
 *
 * create by cd 20161219
 */
function XHMixChart(_dom, _url, _params, _config, _newOption) {
    var xBaseCount = _config.xBaseCount ? _config.xBaseCount : 10;
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(_dom);
    // 指定图表的配置项和数据
    var colors = ['#59ADF3', '#AF89D6', '#FF999A', '#FFCC67', '#86D560'];
    myChart.showLoading();
    $.ajax({
        type: 'POST',  //POST/PUT/DELETE/HEAD
        url: _url,
        data: _params,  //{k:v} 请求数据
        success: function (_data) {	//成功响应的回调
            myChart.hideLoading();
            var _legends = [];
            var _count;
            $.each(_data, function (key, value) {
                _count = value.length;
                return false;
            });
            $.each(_config.series, function (index, source) {
                _legends.push(source.name);
            });
            option = {
                color: colors,
                title: {
                    text: _config.title ? _config.title : '',
                    textStyle: {
                        fontSize: 25
                    },
                    left: '10%'
                },
                tooltip: {
                    trigger: 'axis'
                },
                toolbox: {
                    itemSize: 25,
                    show: true,
                    right: '10%',
                    feature: {
                        mark: {show: true},
                        dataView: {show: true, readOnly: false},
                        magicType: {show: true, type: ['line', 'bar']},
                        restore: {show: true},
                        saveAsImage: {show: true}
                    }
                },
                calculable: true,
                legend: {
                    data: _legends,
                    itemGap: 40,
                    itemHeight: 20,
                    itemWidth: 30

                },
                grid: {
                    top: '10%',
                    left: '10%',
                    right: '10%',
                    bottom: '10%',
                    containLabel: true
                },
                xAxis: [{
                    //设置字体倾斜
                    axisLabel: {
                        interval: 0,
                        rotate: 15,//倾斜度 -90 至 90 默认为0
                        margin: 20,
                        textStyle: {
                            fontWeight: "bolder",
                            color: "#000000",
                            fontSize: 14
                        }
                    },
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: _data.xList
                }],
                yAxis: [{
                    type: 'value',
                    splitArea: {show: true},
                    name: _config.yTitle[0] ? _config.yTitle[0] : '总量',
                    min: 0,
                    position: 'left',
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                    {
                        type: 'value',
                        name: _config.yTitle[1] ? _config.yTitle[1] : '百分率',
                        min: 0,
                        max: 1,
                        position: 'right',
                        axisLabel: {
                            formatter: "{value}"
                        }
                    }
                ],
                dataZoom: [
                    {
                        show: true,
                        start: 0,//数据窗口范围的起始百分比
                        end: (xBaseCount / _count) * 100
                    },
                    {
                        type: 'inside',
                        start: 0,
                        end: 100
                    },
                    {
                        show: true,
                        yAxisIndex: 0,
                        filterMode: 'empty',
                        width: 20,
                        height: '100%',
                        showDataShadow: false,
                        left: '92%'
                    }
                ],
                series: [{
                    name: _config.series[0].name,
                    type: 'bar',
                    data: _data.y1List,


                    label: {
                        normal: {
                            show: true,
                            position: 'top',
                            textStyle: {
                                fontWeight: 'bolder',
                                fontSize: '12'
                            }
                        }
                    }
                }, {
                    name: _config.series[1].name,
                    type: 'line',
                    yAxisIndex: 1,
                    data: _data.y2List,
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,//是否展示
                                textStyle: {
                                    fontWeight: 'bolder',
                                    fontSize: '12'
                                }
                            }
                        }
                    }
                }]
            };
            if (_newOption) option = $.extend(true, option, _newOption);
            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
        },
        error: function () {  //失败响应的回调
            console.log('失败响应的回调.');
            console.log(arguments);
        }
    });
}


/**
 * 饼图的绘制
 *
 * @param _id           --容器ID
 * {
 *      "url":"数据来源",
 *      "params": {"变量名": "值"}
 * }
 * or
 * [
 *      {"name":"项目1","value":"数量1"},
 *      {"name":"项目2","value":"数量2"}
 * ]
 * @param _source       --数据源
 * {
 *      "title": "图表标题"
 * }
 * @param _config       --常用变量
 * @param _newOption    --自定义新的option
 * @constructor
 *
 * create by cd 20161219
 * modify by ck 20170103    提供多种数据来源方式，项名可以从数据源读取，默认参数更改，优化注释
 * modify by ck 20170104    去除对象，防止数据残留
 */
function XHPieChart(_id, _source, _config, _newOption) {
    //如果为string则转为object(转换字符串形式json)
    if(typeof _source == 'string') _source = eval('(' + _source + ')');

    //初始化echarts实例
    var myChart = echarts.init(document.getElementById(_id));
    myChart.showLoading();

    //如果数据源定义了url，则根据url获取数据，否则直接显示
    if(_source.url){
        var _params = _source.params ? _source.params : {};
        $.ajax({
            type: 'POST',               //POST/PUT/DELETE/HEAD
            url: _source.url,
            data: _params,
            async: true,
            dataType: 'json',
            success: function (data) {	//成功响应的回
                dealChart(data);
            }
        });
    }
    else{
        dealChart(_source);
    }
    return myChart;

    //处理参数并渲染
    function dealChart(_data) {
        myChart.hideLoading();
        // 指定图表的配置项和数据
        var colors = ['#AF89D6', '#59ADF3', '#FF999A', '#FFCC67', '#86D560'];
        var keys = [];
        $.each(_data, function (key, value) {
            keys.push(value.name);
        });
        var option = {
            color: colors,
            title: {
                text: _config.title ? _config.title : '',
                x: 'center',
                textStyle: {
                    fontSize: 15
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: "{b}: {c} ({d}%)"
            },
            legend: {
                orient: 'vertical',
                right: '0%',
                top: '5%',
                data: keys,
                itemHeight: 20,
                itemWidth: 20

            },
            textStyle: {
                fontSize: 14
            },
            series: [
                {
                    name: '访问来源',
                    type: 'pie',
                    radius: '90%',
                    center: ['45%', '50%'],
                    data: _data,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        },
                        normal: {
                            label: {
                                show: true,
                                position:'inside',
                                formatter: '{b} : {c} ({d}%)'
                                //formatter: '{b}'            //显示不下只显示名称
                            }
                        },
                        labelLine: {show: true}
                    }
                }
            ]
        };
        if (_newOption) option = $.extend(true, option, _newOption);
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
    }
}